<template>
  <el-scrollbar class="side-scroll-bar" >
    <div class="panel-container">

    <el-collapse v-model="activeNames" class="widget-collapse">

        <el-collapse-item name="2" title="基础组件">
          <template #title>
            基础组件 &nbsp;&nbsp;
          </template>
          <draggable tag="ul" :list="basicFields" item-key="key" :group="{name: 'dragGroup', pull: 'clone', put: false}"
                     :move="checkFieldMove"
                     :clone="handleFieldWidgetClone" ghost-class="ghost" :sort="false">
            <template #item="{ element: fld }">
              <li class="field-widget-item" :title="fld.displayName" @dblclick="addFieldByDbClick(fld)">
                <span><svg-icon :icon-class="fld.icon" class-name="color-svg-icon" />{{getWidgetLabel(fld)}}</span>
              </li>
            </template>
          </draggable>
        </el-collapse-item>

        <el-collapse-item name="3" title="高级组件">
          <template #title>
            高级组件 &nbsp;&nbsp;
          </template>
          <draggable tag="ul" :list="seniorFields" item-key="key" :group="{name: 'dragGroup', pull: 'clone', put: false}"
                     :move="checkFieldMove"
                     :clone="handleFieldWidgetClone" ghost-class="ghost" :sort="false">
            <template #item="{ element: fld }">
              <li class="field-widget-item" :title="fld.displayName" @dblclick="addFieldByDbClick(fld)">
                <span><svg-icon :icon-class="fld.icon" class-name="color-svg-icon" />{{getWidgetLabel(fld)}}</span>
              </li>
            </template>
          </draggable>
        </el-collapse-item>

        <el-collapse-item name="1" title="布局组件">
          <template #title>
            布局组件 &nbsp;&nbsp;
          </template>
          <draggable tag="ul" :list="containers" item-key="key" :group="{name: 'dragGroup', pull: 'clone', put: false}"
                     :clone="handleContainerWidgetClone" ghost-class="ghost" :sort="false"
                     :move="checkContainerMove" @end="onContainerDragEnd">
            <template #item="{ element: ctn }">
              <li class="container-widget-item" :title="ctn.displayName" @dblclick="addContainerByDbClick(ctn)">
                <svg-icon :icon-class="ctn.icon" class-name="color-svg-icon" />
                <div>{{getWidgetLabel(ctn)}}</div>
              </li>
            </template>
          </draggable>
        </el-collapse-item>

        

        <!-- <el-collapse-item name="3" title="高级组件">
          <draggable tag="ul" :list="advancedFields" item-key="key" :group="{name: 'dragGroup', pull: 'clone', put: false}"
                     :move="checkFieldMove"
                     :clone="handleFieldWidgetClone" ghost-class="ghost" :sort="false">
            <template #item="{ element: fld }">
              <li class="field-widget-item" :title="fld.displayName" @dblclick="addFieldByDbClick(fld)">
                <span><svg-icon :icon-class="fld.icon" class-name="color-svg-icon" />{{getWidgetLabel(fld)}}</span>
              </li>
            </template>
          </draggable>
        </el-collapse-item> -->

        <!-- <el-collapse-item name="4" :title="i18nt('designer.customFieldTitle')">
          <draggable tag="ul" :list="customFields" item-key="key" :group="{name: 'dragGroup', pull: 'clone', put: false}"
                     :move="checkFieldMove"
                     :clone="handleFieldWidgetClone" ghost-class="ghost" :sort="false">
            <template #item="{ element: fld }">
              <li class="field-widget-item" :title="fld.displayName" @dblclick="addFieldByDbClick(fld)">
                <span>
                  <svg-icon :icon-class="fld.icon" class-name="color-svg-icon" />{{getWidgetLabel(fld)}}</span>
              </li>
            </template>
          </draggable>
        </el-collapse-item> -->

      </el-collapse>

    </div>
  </el-scrollbar>
</template>

<script>
  import SvgIcon from '@/components/svg-icon'
  import {containers as CONS,seniorFields as SFS,  basicFields as BFS, advancedFields as AFS, customFields as CFS, chartContainers as CHART_CONS,
    chartWidgets as CWS} from "./widgetsConfig"
  import {formTemplates} from './templatesConfig'
  import {addWindowResizeHandler, generateId} from "@/utils/util"
  import i18n, {getLocale} from "@/utils/i18n"
  import axios from 'axios'

  // import ftImg1 from '@/assets/ft-images/t1.png'
  // import ftImg2 from '@/assets/ft-images/t2.png'
  // import ftImg3 from '@/assets/ft-images/t3.png'
  // import ftImg4 from '@/assets/ft-images/t4.png'
  // import ftImg5 from '@/assets/ft-images/t5.png'
  // import ftImg6 from '@/assets/ft-images/t6.png'
  // import ftImg7 from '@/assets/ft-images/t7.png'
  // import ftImg8 from '@/assets/ft-images/t8.png'

  export default {
    name: "FieldPanel",
    mixins: [i18n],
    components: {
      SvgIcon
    },
    props: {
      designer: Object,
    },
    inject: ['getBannedWidgets', 'getDesignerConfig'],
    data() {
      return {
        designerConfig: this.getDesignerConfig(),

        firstTab: 'componentLib',
        // firstTab: 'chartLib',

        activeNames: ['1', '2', '3', '4'],
        metadataActiveNames: ['1', '2', '3', '4'],

        containers: [],
        basicFields: [],
        seniorFields: [],
        advancedFields: [],
        customFields: [],
        chartContainers: [],
        chartWidgets: [],

        metaFields: {
          main: {
            entityName: '',
            entityLabel: '',
            fieldList: [
              {
                type: '',
                icon: '',
                displayName: '',
                options: {},
              }
            ]
          },
          detail: [
            {
              entityName: '',
              entityLabel: '',
              fieldList: [
                {
                  type: '',
                  icon: '',
                  displayName: '',
                  options: {},
                }
              ],

            }
          ]
        },

        formTemplates: formTemplates,
        // ftImages: [
        //   {imgUrl: ftImg1},
        //   {imgUrl: ftImg2},
        //   {imgUrl: ftImg3},
        //   {imgUrl: ftImg4},
        //   {imgUrl: ftImg5},
        //   {imgUrl: ftImg6},
        //   {imgUrl: ftImg7},
        //   {imgUrl: ftImg8},
        // ]
      }
    },
    computed: {
      showFormTemplates() {
        if (this.designerConfig['formTemplates'] === undefined) {
          return true
        }

        return !!this.designerConfig['formTemplates']
      },

      showChartLib() {
        if (this.designerConfig['chartLib'] === undefined) {
          return false
        }

        return !!this.designerConfig['chartLib']
      },

      showMetadataLib() {
        if (this.designerConfig['metadataLib'] === undefined) {
          return false
        }

        return !!this.designerConfig['metadataLib']
      },

    },
    created() {
      if (!!this.designerConfig['chartLib']) {
        this.firstTab = 'chartLib'
      }

      // if (!!this.designerConfig['metadataLib']) {
      //   this.firstTab = 'metadataLib'
      // }

      this.loadWidgets()
    },
    mounted() {
      //
    },
    methods: {
      getMetaFieldLabel(widget) {
        const dName = widget.displayName
        return dName.substring(dName.indexOf('.') + 1, dName.length)
      },

      getWidgetLabel(widget) {
        if (!!widget.alias) {  //优先显示组件别名
          return this.i18n2t(`designer.widgetLabel.${widget.alias}`, `extension.widgetLabel.${widget.alias}`)
        }

        return this.i18n2t(`designer.widgetLabel.${widget.type}`, `extension.widgetLabel.${widget.type}`)
      },

      isBanned(wName) {
        return this.getBannedWidgets().indexOf(wName) > -1
      },

      getFTTitle(ft) {
        const langName = getLocale()
        if (!!ft.i18n && !!ft.i18n[langName]) {
          return ft.i18n[langName].title || ft.title
        } else {
          return ft.title
        }
      },

      loadWidgets() {
        this.containers = CONS.map(con => {
          return {
            key: generateId(),
            ...con,
            displayName: this.i18n2t(`designer.widgetLabel.${con.type}`, `extension.widgetLabel.${con.type}`)
          }
        }).filter(con => {
          return !con.internal && !this.isBanned(con.type)
        })
        

        this.seniorFields = SFS.map(fld => {
          return {
            key: generateId(),
            ...fld,
            displayName: this.i18n2t(`designer.widgetLabel.${fld.type}`, `extension.widgetLabel.${fld.type}`)
          }
        }).filter(fld => {
          return !this.isBanned(fld.type)
        })

        this.basicFields = BFS.map(fld => {
          return {
            key: generateId(),
            ...fld,
            displayName: this.i18n2t(`designer.widgetLabel.${fld.type}`, `extension.widgetLabel.${fld.type}`)
          }
        }).filter(fld => {
          return !this.isBanned(fld.type)
        })

        this.advancedFields = AFS.map(fld => {
          return {
            key: generateId(),
            ...fld,
            displayName: this.i18n2t(`designer.widgetLabel.${fld.type}`, `extension.widgetLabel.${fld.type}`)
          }
        }).filter(fld => {
          return !this.isBanned(fld.type)
        })

        this.customFields = CFS.map(fld => {
          return {
            key: generateId(),
            ...fld,
            displayName: this.i18n2t(`designer.widgetLabel.${fld.type}`, `extension.widgetLabel.${fld.type}`)
          }
        }).filter(fld => {
          return !this.isBanned(fld.type)
        })

        this.chartContainers = CHART_CONS.map(con => {
          return {
            key: generateId(),
            ...con,
            displayName: this.i18n2t(`designer.widgetLabel.${con.type}`, `extension.widgetLabel.${con.type}`)
          }
        }).filter(con => {
          return !con.internal && !this.isBanned(con.type)
        })

        this.chartWidgets = CWS.map(wgt => {
          return {
            key: generateId(),
            ...wgt,
            displayName: this.i18n2t(`designer.widgetLabel.${wgt.type}`, `extension.widgetLabel.${wgt.type}`)
          }
        }).filter(wgt => {
          return !this.isBanned(wgt.type)
        })
      },

      handleContainerWidgetClone(origin) {
        return this.designer.copyNewContainerWidget(origin)
      },

      handleFieldWidgetClone(origin) {
        return this.designer.copyNewFieldWidget(origin)
      },

      /* draggable组件的move钩子是在内部子组件被拖放到其他draggable组件时触发！！ */
      checkContainerMove(evt) {
        return this.designer.checkWidgetMove(evt)
      },

      /* draggable组件的move钩子是在内部子组件被拖放到其他draggable组件时触发！！ */
      checkFieldMove(evt) {
        return this.designer.checkFieldMove(evt)
      },

      onContainerDragEnd(evt) {
        //console.log('Drag end of container: ')
        //console.log(evt)
      },

      addContainerByDbClick(container) {
        this.designer.addContainerByDbClick(container)
      },

      addFieldByDbClick(widget) {
        this.designer.addFieldByDbClick(widget)
      },

      addChartContainerByDbClick(container) {
        this.designer.addChartContainerByDbClick(container)
      },

      addChartByDbClick(chart) {
        this.designer.addChartByDbClick(chart)
      },

      loadFormTemplate(jsonUrl, jsonStr) {
        this.$confirm(this.i18nt('designer.hint.loadFormTemplateHint'), this.i18nt('render.hint.prompt'), {
          confirmButtonText: this.i18nt('render.hint.confirm'),
          cancelButtonText: this.i18nt('render.hint.cancel')
        }).then(() => {
          if (!!jsonStr) {
            this.designer.loadFormJson( JSON.parse(jsonStr) )
            this.$message.success(this.i18nt('designer.hint.loadFormTemplateSuccess'))
            return
          }

          axios.get(jsonUrl).then(res => {
            let modifiedFlag = false
            if (typeof res.data === 'string') {
              modifiedFlag = this.designer.loadFormJson( JSON.parse(res.data) )
            } else if (res.data.constructor === Object) {
              modifiedFlag = this.designer.loadFormJson(res.data)
            }
            if (modifiedFlag) {
              this.designer.emitHistoryChange()
            }

            this.$message.success(this.i18nt('designer.hint.loadFormTemplateSuccess'))
          }).catch(error => {
            this.$message.error(this.i18nt('designer.hint.loadFormTemplateFailed') + ':' + error)
          })
        }).catch(error => {
          console.error(error)
        })
      },

      setMetaFields(metaFields) {
        this.metaFields = metaFields
      }

    }

  }
</script>

<style lang="scss" scoped>
  .color-svg-icon {
    -webkit-font-smoothing: antialiased;
    // color: #7c7d82;
    font-size: 40px;
  }

  .side-scroll-bar {
    :deep(.el-scrollbar__wrap) {
      overflow-x: hidden;
    }
  }

  div.panel-container {
    padding-bottom: 10px;
  }

  .no-bottom-margin :deep(.el-tabs__header) {
    margin-bottom: 0;
  }

  .indent-left-margin {
    :deep(.el-tabs__nav) {
      margin-left: 20px;
    }
  }

  .el-collapse-item :deep(ul) > li {
    list-style: none;
  }

  .widget-collapse {
    border-top-width: 0;

    :deep(.el-collapse-item__header) {
      margin-left: 8px;
      font-style: italic;
      font-weight: bold;
      width: auto;
    }

    :deep(.el-collapse-item__content) {
      padding-bottom: 6px;

      ul {
        padding-left: 10px;  /* 重置IE11默认样式 */
        margin: 0;  /* 重置IE11默认样式 */
        margin-block-start: 0;
        margin-block-end: 0.25em;
        padding-inline-start: 10px;
        display: grid;
        grid-gap: 10px;
        grid-template-columns: repeat(3,1fr);
        &:after {
          content: "";
          display: block;
          clear: both;
        }

        .container-widget-item, .field-widget-item, .chart-container-widget-item, .chart-widget-item {
          //text-align: center; // 居中显示不太美观
          // display: inline-block;
          // height: 32px;
          // line-height: 32px;
          // width: 98px;
          // float: left;
          // margin: 2px 6px 6px 0;
          // cursor: move;
          // white-space: nowrap;
          // text-overflow: ellipsis;
          // overflow: hidden;
          // background: #fff;
          // border: 1px solid #DCDFE6;
          // border-radius: 4px;
          // padding: 0 8px;

          // 修改为网格布局
          border: 1px solid #DCDFE6;
          background: #fff;
          cursor: pointer;
          display: inline-block;
          min-width: 70px;
          text-align: center;
          width: 25%;
          padding-bottom: 6px;
          border-radius: 4px;
          box-sizing: border-box;
          padding-top: 5px;

        }

        .container-widget-item:hover, .field-widget-item:hover, .chart-container-widget-item:hover, .chart-widget-item:hover {
          background: #F1F2F3;
          // border-color: $--color-primary;

          // .color-svg-icon {
          //   color: $--color-primary;
            
          // }
        }

        .chart-container-widget-item, .chart-widget-item {
          cursor: default !important;
        }

        .drag-handler {
          position: absolute;
          top: 0;
          left: 160px;
          background-color: #dddddd;
          border-radius: 5px;
          padding-right: 5px;
          font-size: 11px;
          color: #666666;
        }
      }
    }
  }

  .el-card.ft-card {
    border: 1px solid #8896B3;
  }

  .ft-card {
    margin-bottom: 10px;

    .bottom {
      margin-top: 10px;
      line-height: 12px;
    }

    /*
    .image-zoom {
      height: 500px;
      width: 620px
    }
    */

    .ft-title {
      font-size: 13px;
      font-weight: bold;
    }

    .right-button {
      padding: 0;
      float: right;
    }

    .clear-fix:before, .clear-fix:after {
      display: table;
      content: "";
    }

    .clear-fix:after {
      clear: both;
    }
  }
</style>
<style lang="scss">
  .image-popover {
    width: 750px !important;
  }

</style>
